package com.xxxx;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Hello17FlinkParallelism {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment environment = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        //环境并行度的改变。
        environment.setParallelism(2);

        //数据源
        DataStreamSource<String> source = environment.fromElements("hello shanghai", "hello beijing", "hello shenzhen");
        source.setParallelism(3);
        //转换算子：FlatMap
        SingleOutputStreamOperator<Tuple2<String, Integer>> flatMap = source
                .flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                        String[] split = value.split(" ");
                        for (String word : split) {
                            out.collect(new Tuple2<>(word, 1));
                        }
                    }
                });
        flatMap.setParallelism(5)
                .keyBy(0)
                .sum(1)
                .print().setParallelism(3);

        System.out.println(environment.getExecutionPlan());
        //开始执行
        environment.execute("FlinkParallelism" + System.currentTimeMillis());
    }
}
